#include "sqlrequest.h"

SqlRequest::SqlRequest()
{

}

//Подключение к базе данных локальной apulti
void SqlRequest::connectDB() {
    dataBase = new Database();
    dataBase->connDataPult();
    query = QSqlQuery(mBase);
}

//Внесение параметров в талицу settings
int SqlRequest::settingsAdd(QMap<QString, QString> settings) {
    int idsettings;
    query.clear();
    query.exec(selectSettings + settings["court"] + "'");
    query.first();
    if (query.size() == 0) {
        query.clear();
        query.prepare(addSettings); // подготавливаем запрос
        query.addBindValue(settings["court"]);
        query.addBindValue(settings["system"] );
        query.addBindValue(settings["countJudges"]);
        query.exec();
        query.prepare(idSettings);
        query.exec();
        query.first();
        rec = query.record();
        idsettings = query.value(rec.indexOf("idsettings")).toInt();
    } else {
        query.clear();
        query.exec(updateSettingsStart + settings["system"] + updateSettingsJudges  + settings["countJudges"]  + updateDevicesEnd + settings["court"] + "'");
        query.first();
        query.clear();
        query.exec(selectSettings + settings["court"] + "'");
        query.first();
        rec = query.record();
        idsettings = query.value(rec.indexOf("idsettings")).toInt();
    }
    return idsettings;
}

QJsonObject SqlRequest::tablServerVist() {
    QJsonObject tablServerObject;
    QJsonArray tablServerArray;
    QJsonObject tablObject;
    query.clear();
    query.exec(sqlZapVist);
    if(query.size() != 0) {
        tablServerArray = tablServerObject["tablVis"].toArray();
        for (int i=0; query.next(); i++) {
            tablObject["idvist"] = query.value(0).toInt();
            tablObject["nomer"] = query.value(1).toInt();
            tablObject["pokaz"] = query.value(2).toInt();
            tablObject["activno"] = query.value(3).toInt();
            tablObject["sportsmen"] = query.value(4).toString();
            tablObject["phumse"] = query.value(5).toString();
            tablObject["kategoria"] = query.value(6).toString();
            tablObject["idvistpred"] = query.value(7).toInt();
            tablObject["zaver"] = query.value(8).toInt();
            tablObject["sort"] = query.value(9).toInt();
            tablObject["krug"] = query.value(10).toInt();
            tablServerArray.append(tablObject);

        }
        tablServerObject["tablVis"] = tablServerArray;
    }
    return tablServerObject;
}

QJsonObject SqlRequest::tablServerVistEnd() {
    QJsonObject tablServerObject;
    QJsonArray tablServerArray;
    QJsonObject tablObject;
    query.clear();
    query.exec(sqlZapVistEnd);
    if(query.size() != 0) {
        tablServerArray = tablServerObject["tablVis"].toArray();
        for (int i=0; query.next(); i++) {
            tablObject["idvist"] = query.value(0).toInt();
            tablObject["nomer"] = query.value(1).toInt();
            tablObject["pokaz"] = query.value(2).toInt();
            tablObject["activno"] = query.value(3).toInt();
            tablObject["sportsmen"] = query.value(4).toString();
            tablObject["phumse"] = query.value(5).toString();
            tablObject["kategoria"] = query.value(6).toString();
            tablObject["idvistpred"] = query.value(7).toInt();
            tablObject["zaver"] = query.value(8).toInt();
            tablObject["sort"] = query.value(9).toInt();
            tablObject["krug"] = query.value(10).toInt();
            tablServerArray.append(tablObject);
        }
        tablServerObject["tablVis"] = tablServerArray;
    }
    return tablServerObject;
}

//Добавление пульта
int SqlRequest::addDevice(QMap<QString, QString> devices) {
    int idDevice;
    query.clear();
    query.exec(selectDevicesName + devices["device_name"] + "'");
    if (query.size() == 0) {
        query.clear();
        query.prepare(addDevices);
        query.addBindValue(devices["device_name"]);
        query.addBindValue(devices["device_socketConn"]);
        query.exec();
        query.clear();
        query.prepare(idDevices);
        query.exec();
        query.first();
        rec = query.record();
        idDevice = query.value(rec.indexOf("iddevice")).toInt();
    } else {
        query.first();
        rec = query.record();
        idDevice = query.value(rec.indexOf("iddevice")).toInt();
        query.clear();
        query.exec(updateDevicesStart + devices["device_socketConn"] + updateDevicesSud + "0" + updateDevicesCourt + "0" +  updateDevicesEnd + QString::number(idDevice) +"'");
        query.first();
    }
    return idDevice;
}

//Запроос для имя пульта
QJsonObject SqlRequest::deviceSelect(int idDevice) {
    query.clear();
    QJsonObject device;
    query.exec(selectDevices + "'" + QString::number(idDevice) + "'");
    if (query.size() != 0) {
        query.first();
        rec = query.record();
        device["device_name"] = query.value(rec.indexOf("device_name")).toString();
        device["device_socketConn"] = query.value(rec.indexOf("device_socketConn")).toInt();
    }
    return device;
}

//Присваием устройству номер судьи
void SqlRequest::updateDevice(QMap<QString, int> judges) {
    query.clear();
    query.exec(updateDevicesConnectStart + QString::number(judges["numberJudges"]) + updateDevicesConnectCourt
            + QString::number(judges["kort"]) + updateDevicesConnectEnd
            + QString::number(judges["socket"]) + "'");
    query.first();
}

//Выводим номер судьи
int SqlRequest::selNumSud(int socketConn) {
    int numSud = 0;
    query.clear();
    query.exec(selectSud + QString::number(socketConn) + "'");
    query.first();
    if(query.size() != 0) {
        rec = query.record();
        numSud = query.value(rec.indexOf("device_sudNum")).toInt();
        query.clear();
    }
    query.exec(updateDevicesStart + "-1" + updateDevicesSud + "0" + updateDevicesCourt + "0" + updateDevicesConnEnd + QString::number(numSud) +"'");
    query.first();
    return numSud;
}

//Количество подключенных судей
int SqlRequest::countJudges(int court) {
    query.clear();
    query.exec(selectJudges + QString::number(court) + "'");
    query.first();
    rec = query.record();
    return query.value(rec.indexOf("judgesCount")).toInt();
}

//Json при нажатии кнопки старт
QJsonObject SqlRequest::startVistup(int system) {
    query.clear();
    QJsonObject startvistObject = QJsonObject();
    query.exec(sqlZapID);
    query.first();
    if(query.size() != 0) {
        rec = query.record();
        startvistObject["nomer"] = query.value(rec.indexOf("vistuplenie_nomer")).toInt();
        startvistObject["pokaz"] = query.value(rec.indexOf("vistuplenie_pokaz")).toInt();
        startvistObject["countVistup"] = query.value(rec.indexOf("vistuplenie_pokaz")).toInt();
        if(query.value(rec.indexOf("vistuplenie_pokaz")).toInt() == 1) startvistObject["countVistup"] = 0;
        startvistObject["sportsmen"] = query.value(rec.indexOf("vistuplenie_sportsmen")).toString();
        startvistObject["phumse"] = query.value(rec.indexOf("phumse_name")).toString();
        startvistObject["kategoria"] = query.value(rec.indexOf("vistuplenie_kategoria")).toString();
        startvistObject["idvist"] = query.value(rec.indexOf("idvistuplenie")).toInt();
        startvistObject["system"] = system;
        startvistObject["krugNomer"] = query.value(rec.indexOf("vistuplenie_krugNomer")).toInt();
        startvistObject["idphumse"] = query.value(rec.indexOf("phumse_idphumse")).toInt();
        startvistObject["idvistpred"] = query.value(rec.indexOf("vistuplenie_pred")).toInt();
        query.exec(sqlUpdStartVist  + QString::number(query.value(rec.indexOf("idvistuplenie")).toInt()) + "'");
    }
    return startvistObject;
}

void SqlRequest::stopVistup(QJsonObject obj) {
    query.clear();
    query.exec(sqlUpdStopVist + QString::number(obj["idvitup"].toInt()) + "'");
    query.first();
}

//Сколько пхумсэ выполняется в категории
int SqlRequest::kolPhumKatek(QJsonObject json) {
    int kolPhum;
    query.clear();
    query.exec(sqlCountPhumseStart + QString::number(json["nomer"].toInt())
            + sqlCountPhumse + QString::number(json["krugNomer"].toInt())
            + sqlCountPhumseEnd + json["kategoria"].toString() + "'");
    query.first();
    rec = query.record();
    kolPhum = query.value(rec.indexOf("kolPhum")).toInt();
    return kolPhum;
}

//Подключаем или обновляем судей к серверу
QJsonObject SqlRequest::connectJudges(QJsonObject obj) {
    int judgesNum = obj["judgesNum"].toInt();
    int idperfomance = obj["idperfomance"].toInt();
    QJsonObject judgesObject = QJsonObject();
    QJsonArray judgesArray = QJsonArray();
    QJsonObject judges;
    query.clear();
    query.exec(selectJudgesStart + QString::number(judgesNum) + selectJudgesEnd + QString::number(idperfomance) + "'");
    query.first();
    if(judgesNum != 0) {
        if (query.size() <= 0) {
            query.clear();
            query.prepare(addJudges);
            query.addBindValue(idperfomance);
            query.addBindValue(judgesNum);
            query.exec();
            query.first();
        } else {
            query.clear();
            query.exec(updateJudgesStart + QString::number(judgesNum) + updateJudgesEnd + QString::number(idperfomance) + "'");
            query.first();
        }
        query.clear();
        query.exec(selectJudgesPerfomance + QString::number(idperfomance) + "'");
        if(query.size() != 0) {
            for (int i=0; query.next(); i++) {
                judgesArray = judgesObject["judges"+QString::number(i)].toArray();
                judges["nomersud"] = query.value(0).toInt();
                judgesArray.append(judges);
                judgesObject["judges"+QString::number(i)] = judgesArray;
            }
        }
    }
    return judgesObject;
}

//Количество судей готоввых выставлять оценки за выступление
int SqlRequest::countJudgesPerfomance(int idvist) {
    query.clear();
    query.exec(selectCountJudges + QString::number(idvist) + "'");
    query.first();
    rec = query.record();
    return query.value(rec.indexOf("judgesCount")).toInt();
}

//Добавление оценок судей
void SqlRequest::ocenkiAdd(QJsonObject json) {
    query.clear();
    query.prepare(addOcenki);
    query.addBindValue(json["idvistuplenie"].toInt());
    query.addBindValue(json["nomersud"].toInt());
    query.addBindValue(json["ocenkiT"].toInt());
    query.addBindValue(json["ocenkiP"].toInt());
    query.exec();
}

void SqlRequest::delOcenki(QJsonObject json) {
    query.clear();
    query.exec(delOcenkiStart + QString::number(json["idvitup"].toInt()) + delOcenkiEnd + QString::number(json["delNomerSud"].toInt()) + "'");
    query.first();
}

//Вывод оценок судей
QJsonObject SqlRequest::ocenkiSelect(int idvist) {
    query.clear();
    QJsonArray ocenkiArray;
    QJsonObject ocenkiObject;
    QJsonObject ocenObject;
    accuracy.clear();
    presentation.clear();
    ocenkiObject["command"] = 3;
    query.exec(selectOcenki + QString::number(idvist) + "'");
    int i = 0;
    if(query.size() != 0) {
        ocenkiArray = ocenkiObject["ocenki" + QString::number(i)].toArray();
        while (query.next()) {
            i += 1;
            rec = query.record();
            ocenObject["ocenki_nomsud"] = query.value(rec.indexOf("ocenki_nomsud")).toInt();
            ocenObject["ocenki_t"] = query.value(rec.indexOf("ocenki_t")).toInt();
            ocenObject["ocenki_p"] = query.value(rec.indexOf("ocenki_p")).toInt();
            accuracy.append(query.value(rec.indexOf("ocenki_t")).toInt());
            presentation.append(query.value(rec.indexOf("ocenki_p")).toInt());
            ocenkiArray.append(ocenObject);
        }
        ocenkiObject["ocenki"] = ocenkiArray;
        query.clear();
        query.exec(selectCountOcenki + QString::number(idvist) + "'");
        query.first();
        rec = query.record();
        ocenkiObject["ocenkiCount"] = query.value(rec.indexOf("ocenkiCount")).toInt();
    }
    return ocenkiObject;
}

QJsonObject SqlRequest::total() {
    QJsonObject totalObject;
    int sumAccuracy = 0;
    int sumPresentation = 0;
    auto accuracyMinMax = std::minmax_element(accuracy.begin(), accuracy.end());
    auto presentationMinMax = std::minmax_element(presentation.begin(), presentation.end());
    int accuracySumMinMax = *accuracyMinMax.first+*accuracyMinMax.second;
    int presentationSumMinMax = *presentationMinMax.first+*presentationMinMax.second;
    for(int i=0; i<accuracy.count(); i++) {
        sumAccuracy += accuracy[i];
        sumPresentation += presentation[i];
    }
    totalObject["sumAccuracy"] = sumAccuracy;
    totalObject["sumPresentation"] = sumPresentation;
    totalObject["accuracyMinMax"] = accuracySumMinMax;
    totalObject["presentationMinMax"] = presentationSumMinMax;
    totalObject["accuracyMin"] = *accuracyMinMax.first;
    totalObject["accuracyMax"] = *accuracyMinMax.second;
    totalObject["presentationMin"] = *presentationMinMax.first;
    totalObject["presentationMax"] = *presentationMinMax.second;
    return totalObject;
}

//Завершаем выступление
bool SqlRequest::prynatGrades(int idvist) {
    query.clear();
    query.exec(sqlZaverVist + QString::number(idvist) + "'");
    query.first();
    return true;
}

//Записываем информацию о выступлении, чтобы потом вывести ранг
void SqlRequest::insertRange(QMap<QString, QString> range) {
    query.clear();
    query.prepare(addRang);
    query.addBindValue(range["idvistuplenie"]);
    query.addBindValue(range["totalFirst"]);
    if(range["idvistuplenie_pred"] != "") {
        query.addBindValue(range["totalSecond"]);
        query.addBindValue(range["total"]);
        query.addBindValue(range["idvistuplenie_pred"]);
    } else {
        query.addBindValue(0);
        query.addBindValue(range["totalFirst"]);
        query.addBindValue(0);
    }
    query.addBindValue(range["sumAccuracyObsh"]);
    query.addBindValue(range["sumPresentationObsh"]);
    query.addBindValue(range["sumObsh"]);
    query.addBindValue(range["categories"]);
    query.addBindValue(range["nomer"]);
    query.addBindValue(range["athlethe"]);
    query.addBindValue(range["krugNomer"]);
    query.exec();
}

//Выводим ранг
QJsonObject SqlRequest::selectRange(QString categoria, int krugNomer) {
    query.clear();
    QJsonArray rangArray;
    QJsonObject rangObject;
    QJsonObject rangeObject;
    query.exec(selectRangStart + categoria + selectRang + QString::number(krugNomer) + selectRangEnd);
    rangArray = rangObject["rang"].toArray();
    while (query.next()) {
        rec = query.record();
        rangeObject["rang_tot"] = QString::number(query.value(rec.indexOf("rang_tot")).toDouble()/100, 2, 2);
        rangeObject["rang_athlethe"] = query.value(rec.indexOf("rang_athlethe")).toString();
        rangeObject["rang_sumpres"] = QString::number(query.value(rec.indexOf("rang_sumpres")).toDouble()/100, 2, 2);
        rangeObject["rang_sumobsh"] = QString::number(query.value(rec.indexOf("rang_sumobsh")).toDouble()/10, 1, 1);
        rangArray.append(rangeObject);
    }
    rangObject["rang"] = rangArray;
    return rangObject;
}

//Показываем место спортсмена после выступления
QJsonObject SqlRequest::selectMesto(QString katek, int krugNomer) {
    query.clear();
    QJsonArray mestoArray;
    QJsonObject mestoObj;
    QJsonObject mestoObject;
    int i = 0;
    query.exec(sqlSelectMestoStart + katek + sqlSelectMestoEnd + QString::number(krugNomer) + "'");
    while (query.next()) {
        i += 1;
        rec = query.record();
        mestoArray = mestoObject["mesto" + QString::number(i)].toArray();
        mestoObj["mesto"] = query.value(rec.indexOf("mesto")).toInt();
        mestoObj["idvistuplenie"] = query.value(rec.indexOf("vistuplenie_idvistuplenie")).toInt();
        mestoArray.append(mestoObj);
        mestoObject["mesto" + QString::number(i)] = mestoArray;
    }
    return mestoObject;
}

//Сколько выступлений
int SqlRequest::countAthlethe(QString category, int krugNomer) {
    int kolAthlethe;
    query.clear();
    query.exec(sqlSelectAthletheStart + category + sqlSelectAthletheEnd + "'" + QString::number(krugNomer) + "'");
    query.first();
    rec = query.record();
    kolAthlethe = query.value(rec.indexOf("countAthlethe")).toInt();
    return kolAthlethe;
}

//Сколько выступлений прошло
int SqlRequest::countRang(QString category, int krugNomer) {
    int kolRang;
    query.clear();
    query.exec(sqlSelectRangStart + category + sqlSelectRangEnd + "'" + QString::number(krugNomer) + "'");
    query.first();
    rec = query.record();
    kolRang = query.value(rec.indexOf("countRang")).toInt();
    return kolRang;
}

//Добавлеям выступление с двумя пхумсэ
void SqlRequest::phumseServer(QJsonObject obj) {
    QSqlQuery queryLast = QSqlQuery(mBase);
    int countKrug = 0;
    QString category = obj["cat"].toString();
    QStringList chelServer = obj["str"].toString().split("\n");
    query.clear();
    query.exec(sqlKrugCountStart + category + sqlKrugCountEnd);
    query.first();
    rec = query.record();
    countKrug = query.value(rec.indexOf("countKrug")).toInt();
    if(countKrug == 3) {
        catInt += 1;
        category += QString::number(catInt);
    }
    for (int i=0; i < chelServer.count(); i++) {
        for (int j = 0 ; j < obj["kolPhumse"].toInt(); j ++) {
            if(chelServer[i].trimmed() != "") {
                query.clear();
                query.prepare(addChelVist);
                query.addBindValue(i+1);
                query.addBindValue(j+1);
                query.addBindValue(0);
                query.addBindValue(0);
                query.addBindValue(chelServer[i]);
                switch (j+1) {
                case 1:
                    query.addBindValue(obj["phum1"].toInt());
                    break;
                case 2:
                    query.addBindValue(obj["phum2"].toInt());
                    break;
                }
                query.addBindValue(category);
                if(j == 0) query.addBindValue(0);
                if(j == 1) {
                    queryLast.clear();
                    queryLast.exec(addChelVistLast);
                    queryLast.first();
                    rec = queryLast.record();
                    query.addBindValue(queryLast.value(rec.indexOf("idvistuplenie")).toInt());
                }
                query.addBindValue(obj["krugNomerSetting"].toInt());
                query.exec();
            }
        }
    }
}

void SqlRequest::flagsServer(QJsonObject obj) {
    int krugNomer = 0;
    qWarning()<<"obj = "<<obj;
    QStringList chelServer = obj["str"].toString().split("\n");
    query.clear();
    query.exec(selectKrugVistStart + obj["cat"].toString() + selectKrugVistEnd);
    query.first();
    if(query.size() != 0) {
        rec = query.record();
        switch (query.value(rec.indexOf("vistuplenie_krugNomer")).toInt()) {
        case 1:
            krugNomer = 2;
            break;
        case 2:
            krugNomer = 3;
            break;
        case 3:
            krugNomer = 4;
            break;
        case 4:
            krugNomer = 5;
            break;
        }
    } else {
        krugNomer = 1;
    }
    for (int i=0; i < chelServer.count(); i++) {
        query.clear();
        query.prepare(addChelVist);
        query.addBindValue(i+1);
        query.addBindValue(i+1);
        query.addBindValue(0);
        query.addBindValue(0);
        query.addBindValue(chelServer[i] + ";" + obj["phum1"].toString() + ";" + obj["phum2"].toString());
        query.addBindValue(17);
        query.addBindValue(obj["cat"].toString());
        query.addBindValue(krugNomer);
        query.exec();
    }
}

void SqlRequest::updatePerfomance(QJsonObject obj) {
    query.clear();
    query.exec(sqlUpdVistAc + obj["2"].toString() +
            sqlUpdVistZa + obj["3"].toString() +
            sqlUpdVistSo + obj["4"].toString() +
            sqlUpdVistPo + obj["5"].toString() +
            sqlUpdVistSp + obj["7"].toString() +
            sqlUpdVistID + obj["0"].toString());
    query.first();
}

void SqlRequest::delPerfomance(int idvistuplenie) {
    query.clear();
    query.exec(sqlDelPerfomance + QString::number(idvistuplenie));
    query.first();
}

void SqlRequest::delVist(QJsonObject obj) {
    int idvistup = obj["idvistuplenie"].toString().toInt();
    query.clear();
    query.exec(sqlDelVistSelect + QString::number(idvistup) + "'");
    query.first();
    rec = query.record();
    int vistupPred = query.value(rec.indexOf("vistuplenie_pred")).toInt();
    if (vistupPred == 0) {
        query.clear();
        query.exec(sqlDelVistSelect + QString::number(idvistup+1) + "'");
        query.first();
        rec = query.record();
        vistupPred = query.value(rec.indexOf("vistuplenie_pred")).toInt();
        if(vistupPred == 0) {
            query.clear();
            query.exec(sqlDelVist + QString::number(idvistup) + "'");
            query.first();
        } else {
           idvistup += 1;
           delTwoVistup(idvistup, vistupPred);
        }
    } else {
        delTwoVistup(idvistup, vistupPred);
    }
}

void SqlRequest::delTwoVistup(int idvistup, int idvistupPred) {
    query.clear();
    query.exec(sqlDelVist + QString::number(idvistupPred) + "'");
    query.first();
    query.clear();
    query.exec(sqlDelVist + QString::number(idvistup) + "'");
    query.first();
}

//Вывод оценок судей
QJsonObject SqlRequest::flagsTotal(int idvist) {
    query.clear();
    int sumBlue = 0;
    int sumRed = 0;
    QJsonArray ocenkiArray;
    QJsonObject ocenkiObject;
    QJsonObject ocenObject;
    accuracy.clear();
    presentation.clear();
    query.exec(selectOcenki + QString::number(idvist) + "'");
    int i = 0;
    if(query.size() != 0) {
        while (query.next()) {
            i += 1;
            rec = query.record();
            ocenkiArray = ocenkiObject["ocenki" + QString::number(i)].toArray();
            ocenObject["ocenki_nomsud"] = query.value(rec.indexOf("ocenki_nomsud")).toInt();
            ocenObject["ocenki_t"] = query.value(rec.indexOf("ocenki_t")).toInt();
            ocenObject["ocenki_p"] = query.value(rec.indexOf("ocenki_p")).toInt();
            accuracy.append(query.value(rec.indexOf("ocenki_t")).toInt());
            presentation.append(query.value(rec.indexOf("ocenki_p")).toInt());
            ocenkiArray.append(ocenObject);
            ocenkiObject["ocenki" + QString::number(i)] = ocenkiArray;
            sumBlue = sumBlue + query.value(rec.indexOf("ocenki_t")).toInt();
            sumRed = sumRed + query.value(rec.indexOf("ocenki_p")).toInt();
        }
        query.clear();
        query.exec(selectCountOcenki + QString::number(idvist) + "'");
        query.first();
        rec = query.record();
        ocenkiObject["ocenkiCount"] = query.value(rec.indexOf("ocenkiCount")).toInt();
        ocenkiObject["totalRed"] = sumRed;
        ocenkiObject["totalBlue"] = sumBlue;
    }
    return ocenkiObject;
}

QJsonObject SqlRequest::categoriesRang() {
    query.clear();
    QJsonArray categoriesArray;
    QJsonObject categoriesObject;
    QJsonObject catekObject;
    query.exec(sqlSelectCategoties);
    int i = 0;
    if(query.size() != 0) {
        while (query.next()) {
            i += 1;
            rec = query.record();
            categoriesArray = categoriesObject["categories" + QString::number(i)].toArray();
            catekObject["rang_category"] = query.value(rec.indexOf("rang_category")).toString();
            categoriesArray.append(catekObject);
            categoriesObject["categories" + QString::number(i)] = categoriesArray;
        }
    }
    return categoriesObject;
}

int SqlRequest::nomerKrugCategory(QString category) {
    int nomer = 0;
    query.clear();
    query.exec(sqlNomerKrugSrat + category + sqlNomerKrugEnd);
    query.first();
    rec = query.record();
    nomer = query.value(rec.indexOf("vistuplenie_krug")).toInt();
    return nomer;
}

int SqlRequest::countKrugCategory(QString category) {
    int count = 0;
    query.clear();
    query.exec(sqlKrugCountStart + category + sqlKrugCountEnd);
    query.first();
    rec = query.record();
    count = query.value(rec.indexOf("countKrug")).toInt();
    return count;
}

QJsonObject SqlRequest::krugCategory(QString categoria) {
    query.clear();
    QJsonArray kortArray;
    QJsonObject kort;
    QJsonObject kortObject;

    query.exec(sqlNomerKrugSrat + categoria + sqlNomerKrugEnd);
    kortArray = kortObject["kort"].toArray();
    while (query.next()) {
        rec = query.record();
        kort["nomer"] = query.value(rec.indexOf("vistuplenie_krugNomer")).toInt();
        kortArray.append(kort);
    }
    kortObject["kort"] = kortArray;
    return kortObject;
}

QJsonObject SqlRequest::selectParticipants(QString categoria, int krugNomer) {
    query.clear();
    QJsonArray participantsArray;
    QJsonObject participant;
    QJsonObject participantsObject;
    query.exec(sqlParticipantsSelectSrat + categoria + sqlParticipantsSelect + QString::number(krugNomer) + sqlParticipantsSelectEnd);
    participantsArray = participantsObject["participants"].toArray();
    while (query.next()) {
        rec = query.record();
        participant["nomer"] = query.value(rec.indexOf("vistuplenie_nomer")).toInt();
        participant["sportsmen"] = query.value(rec.indexOf("vistuplenie_sportsmen")).toString();
        participant["zaversheno"] = 0;
        participant["activno"] = 0;
        participantsArray.append(participant);
    }
    participantsObject["participants"] = participantsArray;
    return participantsObject;
}
